package com.mobile.collect.net;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import cn.droidlover.xdroidmvp.kit.NLog;
import cn.droidlover.xdroidmvp.net.NetError;
import cn.droidlover.xdroidmvp.net.NetProvider;
import cn.droidlover.xdroidmvp.net.RequestHandler;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class MyNetProvider implements NetProvider {
    @Override
    public Interceptor[] configInterceptors() {
        return new Interceptor[0];
    }

    @Override
    public void configHttps(OkHttpClient.Builder builder) {

    }

    @Override
    public CookieJar configCookie() {
        return null;
    }

    @Override
    public RequestHandler configHandler() {
        return new RequestHandler() {
            @Override
            public Request onBeforeRequest(Request request, Interceptor.Chain chain) {
                return request;
            }

            @Override
            public Response onAfterRequest(Response response, String result, Interceptor.Chain chain) {
                HttpUrl httpUrl = response.request().url();
                String url = httpUrl.toString();
                NLog.e("onAfterRequest", "url = " + url);
                NLog.e("onAfterRequest", "result = " + result);
                NLog.e("onAfterRequest", "response.code = " + response.code());
                JsonParser jsonParser = new JsonParser();

                JsonElement jsonElement = jsonParser.parse(result);
                JsonObject jsonObject = jsonElement.getAsJsonObject();
                JsonElement statusElement = jsonObject.get("code");
                JsonElement pageElement = jsonObject.get("page");
                int status = statusElement.getAsInt();
                if (status != 1) {
                    jsonObject.remove("data");
                }
                if (null != pageElement) {
                    try {
                        pageElement.getAsJsonObject();
                    } catch (Exception e) {
                        jsonObject.remove("page");
                    }
                }
                Gson gson = new Gson();
                result = gson.toJson(jsonObject);

                MediaType mediaType = response.body().contentType();
                return response.newBuilder().body(ResponseBody.create(mediaType, result)).build();
            }
        };
    }

    @Override
    public long configConnectTimeoutMills() {
        return 0;
    }

    @Override
    public long configReadTimeoutMills() {
        return 0;
    }

    @Override
    public boolean configLogEnable() {
        return false;
    }

    @Override
    public boolean handleError(NetError error) {
        return false;
    }
}
